<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>落地页编辑</span>
      </div>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :max-height="defaultHeight"
        :selection.sync="selection"
        :parse-data="parseData"
        :where="where"
      >
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-form
            :model="where"
            class="ele-form-search"
            label-width="75px"
            @keyup.enter.native="reload"
            @submit.native.prevent
          >
            <div class="app-container">
              <div class="filter-container">
                <el-select
                  v-model="where.bazaar"
                  class="filter-item"
                  clearable
                  placeholder="请选择推广市场"
                  @change="reload"
                >
                  <el-option
                    v-for="item in bazaarList"
                    :key="item.id"
                    :disabled="item.status === 0"
                    :label="
                      `[` +
                      [
                        '',
                        '百度SEM竞价',
                        '百度信息流',
                        '巨量引擎',
                        '搜狗推广',
                        '卧龙推广',
                        '360点睛',
                      ][item.platform] +
                      `] ` +
                      item.name
                    "
                    :value="item.id"
                  />
                </el-select>

                <el-input
                  v-model="where.SiteName"
                  class="filter-item"
                  clearable
                  placeholder="站点名称"
                  style="width: 180px"
                  @clear="reload"
                />

                <el-input
                  v-model="where.DomainUrl"
                  class="filter-item"
                  clearable
                  placeholder="落地页"
                  style="width: 180px"
                  @clear="reload"
                />

                <el-button
                  class="filter-item"
                  icon="el-icon-search"
                  type="primary"
                  @click="reload"
                  >搜索
                </el-button>
                <el-button
                  class="filter-item"
                  icon="el-icon-refresh"
                  style="margin-left: 2px"
                  @click="reset"
                  >重置
                </el-button>
              </div>
            </div>
          </el-form>
        </template>

        <!-- 推广市场列 -->
        <template slot="bazaar" slot-scope="{ row }">
          <template v-for="item in bazaarList">
            <span v-if="item.id === row.bazaar" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </template>

        <!-- AB页状态列 -->
        <template slot="abswitch" slot-scope="{ row }">
          <el-tag :type="['info', 'success'][row.abswitch]" size="mini">
            {{ ["未开启AB页", "已开启AB页"][row.abswitch] }}
          </el-tag>
        </template>

        <!-- 自助恢复列 -->
        <template slot="SiteSource" slot-scope="{ row }">
          <el-tag v-if="!row.issource" size="mini" type="info">未上传</el-tag>
          <el-tag v-if="row.issource" size="mini" type="success">已上传</el-tag>
        </template>

        <!-- 百度统计列 -->
        <template slot="BaiduCode" slot-scope="{ row }">
          <el-tag v-if="!row.BaiduCode" size="mini" type="info">未设置</el-tag>
          <el-tag v-if="row.BaiduCode" size="mini" type="success"
            >已设置</el-tag
          >
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{ row }">
          <el-link
            :underline="false"
            icon="el-icon-eleme"
            type="success"
            @click="openDefault(row, 1)"
            >重置模板
          </el-link>
          <el-link
            :underline="false"
            icon="el-icon-edit-outline"
            type="primary"
            @click="openDefault(row, 2)"
            >编辑模板
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>

    <el-dialog
      width="860px"
      :title="
        `【` +
        editData.SiteName +
        ' - ' +
        editData.DomainUrl +
        `】落地页模板重置`
      "
      @closed="closedResetTemplate"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :visible.sync="resetShowTemplate"
    >
      <el-form ref="form" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="落地页:" prop="id">
              <span>
                {{ editData.DomainUrl }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="上传操作时间:" label-width="120px">
              <span>
                {{ editData.editDate }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="操作日志:">
          <el-input
            v-model="resetTemplateLog"
            :readonly="true"
            :rows="17"
            clearable
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="resetShowTemplate = false">取消操作 </el-button>
        <el-button
          :loading="resetTemplateLoading"
          type="primary"
          @click="resetTemplateEvent"
          >确定重置
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      top="50px"
      width="760px"
      :title="
        `【` +
        editData.SiteName +
        ' - ' +
        editData.DomainUrl +
        `】落地页模板在线编辑`
      "
      @opened="editTemplateEditor"
      @closed="editTemplateUrlSrc = null"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :visible.sync="editShowTemplate"
    >
      <iframe
        width="720px"
        height="600px"
        id="editIframe"
        ref="editIframe"
        :src="editTemplateUrlSrc"
        class="editIframe"
        frameborder="0"
      ></iframe>
      <div slot="footer">
        <el-button @click="editShowTemplate = false">取消操作 </el-button>
        <el-button
          :loading="editTemplateLoading"
          type="primary"
          @click="setEditTemplate"
          >确定同步
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      width="860px"
      :title="
        `【` +
        editData.SiteName +
        ' - ' +
        editData.DomainUrl +
        `】落地页模板编辑`
      "
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      @closed="closedEditCompileTemplates"
      :visible.sync="showEditCompileTemplates"
    >
      <el-form ref="form" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="落地页:" prop="id">
              <span>
                {{ editData.DomainUrl }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="上传操作时间:" label-width="120px">
              <span>
                {{ editData.editDate }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="操作日志:">
          <el-input
            v-model="showEditCompileTemplatesLog"
            :readonly="true"
            :rows="17"
            clearable
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="showEditCompileTemplates = false"
          >明白
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { messageLoading } from "@/panel";
export default {
  name: "SystemTemplateDditor",
  data() {
    return {
      // 表格高度
      defaultHeight: 0,
      // 市场列表
      bazaarList: [],
      // 表格数据接口
      url: "/TemplateEditor/read",
      // 表格列配置
      columns: [
        {
          columnKey: "index",
          type: "index",
          width: 100,
          label: "序号",
          align: "center",
          showOverflowTooltip: true,
        },
        {
          columnKey: "bazaar",
          label: "推广市场",
          showOverflowTooltip: true,
          slot: "bazaar",
        },
        {
          prop: "SiteName",
          label: "站点名称",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "DomainUrl",
          label: "落地页",
          sortable: "custom",
          showOverflowTooltip: true,
          minWidth: 110,
        },
        {
          prop: "abswitch",
          slot: "abswitch",
          label: "AB页切换",
          sortable: "custom",
          showOverflowTooltip: true,
          minWidth: 110,
        },
        {
          prop: "SiteSource",
          slot: "SiteSource",
          label: "模板源码",
          sortable: "custom",
          showOverflowTooltip: true,
          minWidth: 110,
        },
        {
          prop: "BaiduCode",
          slot: "BaiduCode",
          label: "统计代码",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "editDate",
          label: "上次编辑时间",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          columnKey: "action",
          label: "操作",
          width: 200,
          resizable: false,
          slot: "action",
        },
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      editData: {
        SiteName: "",
        DomainUrl: "",
        editDate: "",
        editHtml: "",
      },

      // 是否显示重置模板
      resetShowTemplate: false,
      // 站点重置结果
      resetTemplateLog: "",
      // 重置状态
      resetTemplateLoading: false,
      // 重置时间
      resetTemplateTimer: null,
      // 重置状态次数
      resetTemplateCount: 0,

      // 是否显示模板编辑
      editShowTemplate: false,
      // 编辑模板加载中
      editTemplateLoading: false,
      //模板编辑URL
      editTemplateUrlSrc: null,

      // 是否显示编辑结果
      showEditCompileTemplates: false,
      showEditCompileTemplatesLog: null,
      showEditCompileTemplatesTimer: null,
      showEditCompileTemplatesCount: 0,
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },

  methods: {
    parseData(res) {
      if (res.code === 0) {
        this.bazaarList = res.bazaar;
      }
      return {
        code: res.code,
        data: res.data,
        count: res.count,
        msg: res.msg,
      };
    },

    /*设置表格高度*/
    getHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /* 刷新表格 */
    reload(isPage) {
      let obj = { where: this.where };
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      this.reload();
    },

    /* 显示编辑 */
    openDefault(row, type) {
      this.editData = row;
      if (!this.$hasPermission("templateeditor:save")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      if (!row.url) {
        return this.$message.error("站点URL未配置, 操作失败!");
      }
      if (!row.Domains) {
        return this.$message.error("绑定域名未配置, 操作失败!");
      }
      if (!row.btAddress) {
        return this.$message.error("宝塔WebHook未配置, 操作失败!");
      }
      if (!row.btKey) {
        return this.$message.error("宝塔WebHook密匙未配置, 操作失败!");
      }
      if (!row.aPage) {
        return this.$message.error("站点目录未配置, 操作失败!");
      }
      if (!row.SiteSource) {
        return this.$message.error("落地页未上传源码, 操作失败!");
      }
      const loading = messageLoading("正在请求中..");
      this.$http
        .post(
          "/TemplateEditor/" + (type == 1 ? "defaultExists" : "editExists"),
          row
        )
        .then((res) => {
          loading.close();
          if (res.data.code === 0) {
            if (type === 1) {
              this.resetTemplateCount = 0;
              this.resetTemplateLog = "暂无消息，待操作";
              this.resetShowTemplate = true;
            } else {
              this.editTemplateUrlSrc = res.data.url;
              this.editShowTemplate = true;
            }
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },

    /* 重置模板 */
    closedResetTemplate() {
      this.resetTemplateCount = 0;
      if (this.resetTemplateTimer) {
        clearInterval(this.resetTemplateTimer);
      }
    },

    closedEditCompileTemplates() {
      this.showEditCompileTemplatesCount = 0;
      if (this.showEditCompileTemplatesTimer) {
        clearInterval(this.showEditCompileTemplatesTimer);
      }
    },

    /* 重置模板 */
    getresetTemplateLogs() {
      this.resetTemplateCount++;
      this.resetTemplateLog =
        this.resetTemplateLog + "正在加载远程日志, 请耐心等待. \n";
      this.$http
        .post("/TemplateEditor/resetTemplateLog", this.editData)
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.msg) {
              if (res.data.msg.indexOf("检测系统环境") > -1) {
                this.resetTemplateLog = res.data.msg;
                if (this.resetTemplateTimer) {
                  clearInterval(this.resetTemplateTimer);
                }
              }
            }
          }
        });
      if (this.resetTemplateCount === 5) {
        this.resetTemplateLog =
          this.resetTemplateLog + "站点URL识别失败, 远程日志加载失败. \n";
        if (this.resetTemplateTimer) {
          clearInterval(this.resetTemplateTimer);
        }
      }
    },

    /* 重置模板 */
    resetTemplateEvent() {
      this.$confirm("此操作将会重置落地页模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.resetTemplateLoading = true;
          this.resetTemplateLog = "正在重置站点模板请稍后. \n";
          this.$http
            .post("/TemplateEditor/resetTemplate", this.editData)
            .then((res) => {
              this.resetTemplateLoading = false;
              if (res.data.code === 0) {
                this.reload(true);
                this.resetTemplateTimer = setInterval(
                  this.getresetTemplateLogs,
                  5000
                );
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  dangerouslyUseHTMLString: true,
                });
              } else {
                this.resetTemplateLog =
                  this.resetTemplateLog + "站点模板重置失败, 网络异常.\n";
                this.$message.error({
                  type: "error",
                  message: res.data.msg,
                  dangerouslyUseHTMLString: true,
                });
              }
            })
            .catch((e) => {
              this.$message.error(e.message);
              this.resetTemplateLoading = false;
              this.resetTemplateLog =
                this.resetTemplateLog + "站点模板重置失败, 网络异常.\n";
            });
        })
        .catch(() => {
          this.resetShowTemplate = false;
          this.$message({
            type: "info",
            message: "已取消重置",
          });
        });
    },

    loadTemplateEditor(iframe) {
      let element = iframe.contentWindow || iframe.contentDocument;
      if (element) {
        let editor = element.CKEDITOR || { version: null };
        if (!editor.version) {
          return this.$message.error({
            type: "error",
            message: "模板编辑引擎加载失败, 请刷新页面重试!",
          });
        }
        let _div = element.document.getElementsByTagName("div");
        for (let i = 0; i < _div.length; i++) {
          if (_div[i].getAttribute("contenteditable")) {
            editor.inline(_div[i]);
          }
        }
      }
    },

    editTemplateEditor() {
      let iframe = this.$refs.editIframe;
      // window.frames["editIframe"];
      if (iframe) {
        if (iframe.attachEvent) {
          iframe.attachEvent("onload", () => {
            this.loadTemplateEditor(iframe);
          });
        } else {
          iframe.onload = () => {
            this.loadTemplateEditor(iframe);
          };
        }
      }
    },

    setEditTemplate() {
      this.editTemplateLoading = true;
      this.editData.editHtml = "";
      let element = this.$refs.editIframe.contentWindow;
      //window.frames["editIframe"];
      //if (iframe) {
      //let element = iframe.contentWindow || iframe.contentDocument;
      if (element) {
        let editor = element.CKEDITOR || { version: null };
        if (!editor.version) {
          return this.$message.error({
            type: "error",
            message: "模板编辑引擎加载失败, 请刷新页面重试!",
          });
        }
        for (let i in editor.instances) {
          if (editor.instances[i]) {
            editor.instances[i].destroy();
          }
        }
        this.editData.editHtml = encodeURIComponent(
          element.document.body.innerHTML
        );
      }
      // }
      const loading = messageLoading("正在请求中..");
      let iframe = this.$refs.editIframe;  //111111
      this.$http
        .post("/TemplateEditor/compileTemplate", this.editData)
        .then((res) => {
          loading.close();
          this.editTemplateLoading = false;
          if (iframe) {
            this.loadTemplateEditor(iframe);
          }
          if (res.data.code === 0) {
            this.showEditCompileTemplatesCount = 0;
            this.compileEditTemplate();
          } else {
            this.$message.error({
              type: "error",
              message: res.data.msg,
              dangerouslyUseHTMLString: true,
            });
          }
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
          this.editTemplateLoading = false;
        });
    },

    geteditTemplateLoadingLogs() {
      this.showEditCompileTemplatesCount++;
      this.showEditCompileTemplatesLog =
        this.showEditCompileTemplatesLog + "正在加载远程日志, 请耐心等待. \n";
      this.$http
        .post("/TemplateEditor/resetTemplateLog", this.editData)
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.msg) {
              if (res.data.msg.indexOf("检测系统环境") > -1) {
                this.showEditCompileTemplatesLog = res.data.msg;
                if (this.showEditCompileTemplatesTimer) {
                  clearInterval(this.showEditCompileTemplatesTimer);
                }
              }
            }
          }
        });
      if (this.showEditCompileTemplatesCount === 5) {
        this.showEditCompileTemplatesLog =
          this.showEditCompileTemplatesLog +
          "站点URL识别失败, 远程日志加载失败. \n";
        if (this.showEditCompileTemplatesTimer) {
          clearInterval(this.showEditCompileTemplatesTimer);
        }
      }
    },

    compileEditTemplate() {
      this.$confirm("此操作将会覆盖落地页模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.editTemplateLoading = true;
          this.showEditCompileTemplates = true;
          this.showEditCompileTemplatesLog = "正在同步站点模板请稍后. \n";
          const loading = messageLoading("正在请求中..");
          this.$http
            .post("/TemplateEditor/compileTemplates", this.editData)
            .then((res) => {
              loading.close();
              this.editTemplateLoading = false;
              if (res.data.code === 0) {
                this.reload(true);
                this.showEditCompileTemplatesTimer = setInterval(
                  this.geteditTemplateLoadingLogs,
                  5000
                );
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  dangerouslyUseHTMLString: true,
                });
              } else {
                this.showEditCompileTemplatesLog =
                  this.showEditCompileTemplatesLog +
                  "站点模板同步失败, 网络异常.\n";
                this.$message.error({
                  type: "error",
                  message: res.data.msg,
                  dangerouslyUseHTMLString: true,
                });
              }
            })
            .catch((e) => {
              loading.close();
              this.editTemplateLoading = false;
              this.showEditCompileTemplatesLog =
                this.showEditCompileTemplatesLog +
                "站点模板同步失败, 网络异常.\n";
              this.$message.error(e.message);
            });
        })
        .catch(() => {
          this.showResetTemplate = false;
          this.$message({
            type: "info",
            message: "已取消同步",
          });
        });
    },
  },
};
</script>
